package com.android.readcard.read;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.inter.UpLoadListener;
import com.android.readcard.utils.BleGlobUtils;
import com.android.readcard.utils.UploadCardUtils;
import com.kaer.sdk.IDCardItem;
import com.kaer.sdk.bt.BtReadClient;
import com.kaer.sdk.utils.CardCode;
import com.kaeridcard.client.BtReaderClient;


/**
 * KT8003读卡
 * 2017/8/24
 * 张鹏
 */
public class Kt8003ConnectUtils {
    private BluetoothDevice remoteDevice;
    private String bleAddress;

    private String name, sex, nation, id_num, address, sign_office, to, from, born;
    private String birth_year, birth_month, birth_day, sign_data, photoHeard;
    private Bitmap photo;
    private String bleName;
    private String bluetoothName = "";
    // 注册成功失败监听
    private UpLoadListener mOnUpLoadListener;
    private BtReadClient mBtReadClient;
    private ReadAsync async;
    private Handler kAmHandler;

    private String bluetoothType;

    public Kt8003ConnectUtils(String bluetoothType, BtReadClient mBtReadClient,
                              BluetoothDevice remoteDevice, String bleName, String bleAddress,
                              final String bluetoothName, final UpLoadListener mOnUpLoadListener) {
        this.bluetoothType = bluetoothType;
        this.mBtReadClient = mBtReadClient;
        this.remoteDevice = remoteDevice;
        this.bleName = bleName;
        this.bleAddress = bleAddress;
        this.bluetoothName = bluetoothName;
        this.mOnUpLoadListener = mOnUpLoadListener;
    }

    public void connect(BtReaderClient mClient) {
        this.mClient = mClient;

        if (mBtReadClient.getBtState() == 0) {
            if (remoteDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                // 已绑定的进入连接
                boolean b = mBtReadClient.connectBt(remoteDevice);
                if (b) {
                    // 子线程同步调用
                    async = new ReadAsync();
                    async.execute();
                } else {
                    setErr("蓝牙连接失败:b=" + b);
                }
            } else {
                setErr("蓝牙未配对");
            }

        } else if (mBtReadClient.getBtState() == 2) {
            if (mBtReadClient.disconnectBt()) {
                setErr("设备已断开连接");
            } else {
                setErr("断开连接失败");
            }
        }
    }

    private void setErr(String err) {
        mOnUpLoadListener.onErrUpLoad(2, err);
    }

    private BtReaderClient mClient;

    /**
     * 断开连接
     */
    public void stopConnect() {
        try {
            if (mClient != null) {
                mClient.disconnectBt();
            }
            if (mBtReadClient != null) {
                mBtReadClient.disconnect();
                mBtReadClient.disconnectBt();
            }
            Log.e("项目异常Kt8003", "------Kt8003断开连接------" + "");
        } catch (Exception e) {
            Log.e("项目异常Kt8003", "------Kt8003断开失败------" + e.toString());
            setErr("断开连接异常");
        }

    }

    /**
     * KT8003 所需
     */
    class ReadAsync extends AsyncTask<Intent, Integer, IDCardItem> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected IDCardItem doInBackground(Intent... params) {
            if (mBtReadClient != null) {
                IDCardItem item = mBtReadClient.readCertWithBlocking();
                return item;
            } else {
                setErr("读取失败:mBtReadClient为空");
                return null;
            }
        }

        @Override
        protected void onPostExecute(IDCardItem result) {
            super.onPostExecute(result);
            updateResult(result);
        }
    }

    /**
     * KT8003 所需
     */
    private void updateResult(IDCardItem arg0) {

        if (arg0.retCode == 1) {
            updateView(arg0);
        } else {
            setErr(CardCode.errorCodeDescription(arg0.retCode));
        }
    }

    /**
     * KT8003 所需
     */
    private void updateView(IDCardItem item) {
        photo = item.picBitmap;
        photoHeard = BleGlobUtils.replaceBlank(
                BleGlobUtils.bitmapToBase64(photo)); //头像
        name = item.partyName.toString().trim(); //名字
        sex = item.gender; //性别
        nation = item.nation; //民族
        born = item.bornDay.substring(0, 4) + item.bornDay.substring(4, 6)
                + item.bornDay.substring(6, 8);  //出生年月日
        birth_year = item.bornDay.substring(0, 4);
        birth_month = item.bornDay.substring(4, 6);
        birth_day = item.bornDay.substring(6, 8);
        address = item.certAddress;//住址
        id_num = item.certNumber;//证件号
        sign_office = item.certOrg;//签发机关
        String expDate = item.expDate;
        String effDate = item.effDate;
        from = effDate.substring(0, 4) +
                effDate.substring(4, 6) +
                effDate.substring(6, 8);

        if (expDate.contains("长期")) {
            sign_data = item.effDate.substring(0, 4) + "."
                    + item.effDate.substring(4, 6) + "." +
                    item.effDate.substring(6, 8)
                    + "--" + expDate.trim();
            to = "长期";
        } else {
            to = expDate.substring(0, 4) +
                    expDate.substring(4, 6) +
                    expDate.substring(6, 8);
            sign_data = item.effDate.substring(0, 4) + "."
                    + item.effDate.substring(4, 6) + "." +
                    item.effDate.substring(6, 8) + "--" +
                    item.expDate.substring(0, 4) + "."
                    + item.expDate.substring(4, 6) + "."
                    + item.expDate.substring(6, 8);
        }
        String chuanMa = UploadCardUtils.getChuanMa(bleName, bleAddress);// 获取串码
// 获取身份证数据
        ReadCardInfo cardInfo = UploadCardUtils.getCardInfo(bluetoothName, address, photoHeard, sex, id_num, nation,
                sign_office, to, name, from, born, sign_data, birth_year,
                birth_month, birth_day, photo);

        // 获取读卡上传数据,使用时需要把data转换成json和串码一起上传
        CardData cardData = UploadCardUtils.getData(bluetoothType, address, photoHeard, sex, id_num, nation,
                sign_office, to, name, from, born, sign_data, birth_year,
                birth_month, birth_day, photo);

        mOnUpLoadListener.onSucUpLoad(cardInfo, cardData, chuanMa);
    }


}
